package com.example.mo.uploadfilehttpdemo;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonUploadOnClick(View view) {
        String fileName = "android.txt";
        String dataToUpload = "hello from android.";
        ((TextView) findViewById(R.id.textView)).setText("");
        UploadFilesTask upt = new UploadFilesTask();
        upt.execute(dataToUpload.getBytes(),fileName.getBytes());//参数1为待上传数据，参数2为文件名
    }

    private class UploadFilesTask extends AsyncTask<byte[], Integer, String> {
        @Override
        protected String doInBackground(byte[]... data) {
            long time = System.currentTimeMillis();
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            DataInputStream inStream = null;
            String uploaded_file_name = new String(data[1]);
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "----WebKitFormBoundary" + time;
            String urlString = "http://159.226.205.43:8080/UploadFile/UploadFile.jsp";
            try {
                //------------------ CLIENT REQUEST
                // open a URL connection to the Servlet
                URL url = new URL(urlString);
                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                // Allow Inputs
                conn.setDoInput(true);
                // Allow Outputs
                conn.setDoOutput(true);
                // Don't use a cached copy.
                conn.setUseCaches(false);
                // Use a post method.
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + uploaded_file_name + "\"" + lineEnd); // uploaded_file_name is the Name of the File to be uploaded
                dos.writeBytes(lineEnd);
                dos.write(data[0]);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                Log.e("Debug", "error: " + ex.getMessage(), ex);
            } catch (IOException ioe) {
                Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            }
            //------------------ read the SERVER RESPONSE
            try {
                inStream = new DataInputStream(conn.getInputStream());
                byte[] response_data = new byte[1024];
                inStream.read(response_data,0,1024);
                inStream.close();
                return new String(response_data);
            } catch (IOException ioex) {
                Log.e("Debug", "error: " + ioex.getMessage(), ioex);
            }
            return null;
        }


        protected void onProgressUpdate(Integer... progress) {
            //设置进度，此函数由ui线程调用
        }

        protected void onPostExecute(String result) {
            if (result == null)
                return;

            ((TextView) findViewById(R.id.textView)).setText(result);

        }
    }
}


